package top.yueyazhui.vhr.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import top.yueyazhui.vhr.mapper.HrMapper;
import top.yueyazhui.vhr.model.Hr;
import top.yueyazhui.vhr.util.HrUtil;

import java.util.List;

@Service
public class HrService implements UserDetailsService {

    @Autowired
    HrMapper hrMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(username);
        if(hr == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        hr.setRoles(hrMapper.getHrRolesById(hr.getId()));
        return hr;
    }

    public List<Hr> getAll(String keyword) {
        return hrMapper.getAll(HrUtil.getCurrentHr().getId(), keyword);
    }

    public Integer update(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    public Integer delete(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }

    public List<Hr> getAllHrExceptCurrentHr() {
        return hrMapper.getAllHrExceptCurrentHr(HrUtil.getCurrentHr().getId());
    }

    public Integer updatePassword(String oldPass, String pass, String checkPass, Integer userId) {
        Hr hr = hrMapper.selectByPrimaryKey(userId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(oldPass, hr.getPassword())) {
            return -1;
        }
        if(!pass.matches("[0-9a-zA-Z!@#$%^&*]{3,}")) {
            return -2;
        }
        if(!pass.equals(checkPass)) {
            return -3;
        }
        String encodePassword = encoder.encode(pass);
        if(hrMapper.updatePassword(userId, encodePassword) == 1) {
            return 1;
        }
        return 0;
    }
}
